package LeetCode.leetcode15;

import java.util.*;

public class Review2 {
    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        new Review2().threeSum(nums);
    }
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 3) {return res;}
        Arrays.sort(nums);
        int i = 0, j = nums.length - 1 , k = 1;
        while(i < j){
            if (i > 0 && nums[i] == nums[i - 1]) {
                i++;
                continue;
            }
            k = i + 1;
            while (k < j) {
                if (k > i + 1 && nums[k] == nums[k - 1]) {
                    k++;
                    continue;
                }
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[k], nums[j]));
                    k++;
                    j--;
                } else if (sum < 0) {
                    k++;
                } else {
                    j--;
                }
            }
            i++;
            j = nums.length - 1;
        }
        return  res;
    }
}
